//
//  addAdressVC.m
//  ZPSALE
//
//  Created by tmosport on 14-6-6.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "addAdressVC.h"
#import "MBProgressHUD.h"

#define FirstComponent 0
#define SubComponent 1
#define ThirdComponent 2

@interface addAdressVC ()
@property NSInteger toggle;
@property (strong, nonatomic) UIPickerView *pickerView;
@property (nonatomic, strong) UIView *viewPicker;
@property (nonatomic,retain) NSArray* firstRegion;
@property (nonatomic,retain) NSArray* secondRegion;
@property (nonatomic,retain) NSArray* thridRegion;
@property(nonatomic,retain)NSArray* selectArray;
@property (strong, nonatomic) IBOutlet UITextField *reciverName;
@property (strong, nonatomic) IBOutlet UITextField *mobileNum;
@property (strong, nonatomic) IBOutlet UITextField *extInfo;

@end

@implementation addAdressVC

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNavigationItem];
    [self dataInit];
    [self setupPickerView];
    [self setupTableView];
    if (_addrId >0 ) {
        [self initContent];
    }

    self.title =_addrId > 0 ? @"修改地址" : @"新增地址";
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]
                                             initWithTitle:@"保存"
                                             style:UIBarButtonItemStyleBordered
                                             target:self
                                             action:@selector(saveAdress:)];
}

-(void)setNavigationItem {
   
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)initContent
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *params = @{@"memberid": _memberId,
                             @"addrid": [NSString stringWithFormat:@"%d",_addrId],
                             @"access_token":_token};
    [manager POST:APIURL@"myzhenpin/getMyAddress.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *addContentDic;
        addContentDic= (NSDictionary *)responseObject;
        if (addContentDic[@"result"]) {
            NSDictionary *resultDic = addContentDic[@"result"];
            //编辑地址时初始化
            _reciverName.text = resultDic[@"receiver"];
            _mobileNum.text = resultDic[@"phone"];
            _extInfo.text = resultDic[@"address"];
            _selectArray = @[resultDic[@"provinceRegionId"],
                             resultDic[@"cityRegionId"],
                             resultDic[@"townRegionId"]
                             ];
            NSString *cellText = [NSString stringWithFormat:@"%@ %@ %@",resultDic[@"province"],resultDic[@"city"],resultDic[@"town"]];
            NSIndexPath *IP = [NSIndexPath indexPathForRow:2 inSection:0];
            UITableViewCell *currentCellSelected = [self.tableView cellForRowAtIndexPath:IP];
            currentCellSelected.textLabel.text = cellText;
            [self.tableView reloadData];
        }else{
            UIAlertView *notice = [[UIAlertView alloc]initWithTitle:@"数据异常" message:@"请稍后重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [notice show];
            return;
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DO:错误捕获
    }];
}
- (void)setupTableView
{
    UIView *footerView = [UIView new];
    self.tableView.tableFooterView = footerView;
}
- (void)setupPickerView
{
    self.toggle = 0;
    _viewPicker = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2, 320, 258)];
    UIToolbar* toolbar = [[UIToolbar alloc] init];
    toolbar.frame=CGRectMake(0,0,320,44);
    toolbar.barStyle = UIBarStyleBlackOpaque;
    UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    
    UIBarButtonItem* cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消"
                                                                   style:UIBarButtonItemStyleDone target:self
                                                                  action:@selector(docancel:)];
    
    UIBarButtonItem* titleButton = [[UIBarButtonItem alloc] initWithTitle:@"请选择所在地区"
                                                                     style:UIBarButtonItemStyleDone target:nil
                                                                    action:nil];
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:@"确定"
                                                                     style:UIBarButtonItemStyleDone target:self
                                                                    action:@selector(saveChoice:)];
    [toolbar setItems:[NSArray arrayWithObjects:cancelButton,flexibleSpaceLeft,titleButton, flexibleSpaceLeft, doneButton, nil]];
    _pickerView = [[UIPickerView alloc]init] ;
    _pickerView.frame=CGRectMake(0, 44, 320,216);
    _pickerView.delegate = self;
    _pickerView.showsSelectionIndicator = YES;
    _pickerView.hidden = YES;
    
    [_viewPicker addSubview:_pickerView];
    [_viewPicker addSubview:toolbar];
    [self.view addSubview:_viewPicker];
    _viewPicker.hidden = YES;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 2)
    {
           // [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:YES];
            [self bringUpPickerViewWithRow:indexPath];
    }
}

- (void)bringUpPickerViewWithRow:(NSIndexPath*)indexPath
{
    
    [_reciverName resignFirstResponder];
    [_mobileNum resignFirstResponder];
    [_extInfo resignFirstResponder];
//    UITableViewCell *currentCellSelected = [self.tableView cellForRowAtIndexPath:indexPath];
    [UIView animateWithDuration:0.5f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^
     {
         self.viewPicker.hidden = NO;
         self.pickerView.hidden = NO;
         self.viewPicker.center = (CGPoint){160, SCREEN_HEIGHT - self.viewPicker.frame.size.height/2 -60};
     }
                     completion:nil];
}

- (void)hidePickerView
{
    [UIView animateWithDuration:0.5f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^
     {
         self.viewPicker.center = (CGPoint){160, 800};
     }
                     completion:^(BOOL finished)
     {
         self.pickerView.hidden = YES;
         self.viewPicker.hidden = YES;
     }];
}

- (void)docancel:(id)sender
{
    [self hidePickerView];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.toggle = 0;
    if (component==0) {
        NSDictionary *_dict=[self.firstRegion objectAtIndex:row];
        NSString *childRegionId = _dict[@"regionId"];
        [self getChildReginData:childRegionId];
        [pickerView selectedRowInComponent:1];
        [pickerView reloadComponent:1];
        [pickerView selectedRowInComponent:2];
    }
    if (component==1) {
        NSDictionary *_dict=[self.secondRegion objectAtIndex:row];
        NSString *childRegionId = _dict[@"regionId"];
        [self getThirdReginData:childRegionId];
        [pickerView selectRow:0 inComponent:2 animated:YES];
        [pickerView reloadComponent:2];
    }
    [pickerView reloadComponent:2];
}

- (void)saveChoice:(id)sender
{
    //保存所在地
    NSIndexPath *ip = [self.tableView indexPathForSelectedRow];
    UITableViewCell *currentCellSelected = [self.tableView cellForRowAtIndexPath:ip];

    NSInteger one = [self.pickerView selectedRowInComponent:0];
    NSInteger two = [self.pickerView selectedRowInComponent:1];
    NSInteger three = [self.pickerView selectedRowInComponent:2];
    
    NSDictionary *_dict=[self.thridRegion objectAtIndex:three];
    NSString *regionPath = _dict[@"regionPath"];
    
    _selectArray = [regionPath componentsSeparatedByString:@","];
    
    NSString *province =[ NSString stringWithFormat:@"%@",[self.firstRegion objectAtIndex:one][@"localName"]];
    NSString *city =[ NSString stringWithFormat:@"%@",[self.secondRegion objectAtIndex:two][@"localName"]];
    NSString *town =[ NSString stringWithFormat:@"%@",[self.thridRegion objectAtIndex:three][@"localName"]];
    NSString *cellText = [NSString stringWithFormat:@"%@,%@,%@",province,city,town];
    currentCellSelected.textLabel.text = cellText;
    [self.tableView reloadData];
    [self hidePickerView];
}

- (void)saveAdress:(id)sender
{
    //新增地址
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *_receiver = _reciverName.text;
    NSString *_phone = _mobileNum.text;
    NSString *_address = _extInfo.text;
    NSString* provinceRegionId,*cityRegionId,*townRegionId;
    if ([_selectArray count] >= 3) {
        provinceRegionId = [NSString stringWithFormat:@"%@",[_selectArray objectAtIndex:0]];
        cityRegionId = [NSString stringWithFormat:@"%@",[_selectArray objectAtIndex:1]];
        townRegionId = [NSString stringWithFormat:@"%@",[_selectArray objectAtIndex:2]];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择所在地区" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    if ([_receiver length] == 0 ||[_receiver isEqual:[NSNull null]] ) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"保存失败" message:@"请输入收货人" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;
    }
    if ([_phone length] == 0 ||[_phone isEqual:[NSNull null]] ) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"保存失败" message:@"请输入手机号码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;
    }
    if ([_address length] == 0 ||[_address isEqual:[NSNull null]] ) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"保存失败" message:@"请输入详细地址" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;
    }//输入验证


    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.dimBackground = YES;
    HUD.labelText = @"更新地址....";
    if (_addrId > 0 ) {
        NSDictionary *params = @{@"memberid": _memberId,
                                 @"addrId":[NSString stringWithFormat:@"%d",_addrId],
                                 @"receiver": _receiver,
                                 @"provinceRegionId": provinceRegionId,
                                 @"cityRegionId": cityRegionId,
                                 @"townRegionId": townRegionId,
                                 @"address": _address,
                                 @"phone": _phone,
                                 @"access_token":_token};
        [manager POST:APIURL@"myzhenpin/updateAddress.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary *addContentDic;
        addContentDic= (NSDictionary *)responseObject;
            if ([addContentDic[@"addrId"] intValue] > 0) {
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(2);
                    HUD.mode = MBProgressHUDModeText;
                    HUD.labelText = @"更新成功!";
                }completionBlock:^{
                    sleep(1);
                    [HUD hide:YES afterDelay:3];
                [self.navigationController popViewControllerAnimated:YES];
                }];
                
            }else{
                UIAlertView *notice = [[UIAlertView alloc]initWithTitle:@"数据异常" message:@"请稍后重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [notice show];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //TODO:接口失败
        }];

    }else{
    
    NSDictionary *params = @{@"memberid": _memberId,
                             @"receiver": _receiver,
                             @"provinceRegionId": provinceRegionId,
                             @"cityRegionId": cityRegionId,
                             @"townRegionId": townRegionId,
                             @"address": _address,
                             @"phone": _phone,
                             @"access_token":_token};
    [manager POST:APIURL@"myzhenpin/addAddress.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *logResult;
        logResult= (NSArray *)responseObject;
        if ([[logResult valueForKey:@"result"]  isEqualToNumber:[NSNumber numberWithBool:YES]]) {
            [self.navigationController popViewControllerAnimated:YES];
            //保存成功自动后退
        }else{
            UIAlertView *notice = [[UIAlertView alloc]initWithTitle:@"保存失败" message:@"请完整填写表单" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [notice show];
//(@"激活失败了");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DO:错误捕获
    }];
    }

}

- (void)dataInit{
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger GET:APIURL@"orders/initTopRegions.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *logDic = (NSDictionary *)responseObject;
        _firstRegion = logDic[@"firstRegion"];
        _secondRegion = logDic[@"secondRegion"];
        _thridRegion= logDic[@"thridRegion"];
        [self.pickerView reloadAllComponents];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//DO:错误捕获
    }];
}

- (void)getChildReginData:(NSString *)regionId
{
    NSDictionary *params = @{@"regionpid": regionId
                             };
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger GET:APIURL@"orders/getChildrenRegions.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *logDic = (NSDictionary *)responseObject;
        _secondRegion = logDic[@"secondRegion"];
        _thridRegion= logDic[@"thridRegion"];
        [self.pickerView reloadComponent:SubComponent];
        [self.pickerView reloadComponent:ThirdComponent];
        [self.pickerView selectRow:0 inComponent:SubComponent animated:YES];
        [self.pickerView selectRow:0 inComponent:ThirdComponent animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DO:错误捕获
    }];
}
- (void)getThirdReginData:(NSString *)regionId
{
    NSDictionary *params = @{@"regionpid": regionId
                             };
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger GET:APIURL@"orders/getChildrenRegions.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _thridRegion = responseObject[@"thridRegion"];
       
        [self.pickerView reloadComponent:ThirdComponent];
         [self.pickerView selectRow:0 inComponent:ThirdComponent animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       //Do:错误捕获
    }];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

{
    UILabel *myView = nil;
    myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 120, 24)];
    myView.textAlignment = NSTextAlignmentCenter;
    myView.font = [UIFont systemFontOfSize:14];         //用label来设置字体大小
    myView.backgroundColor = [UIColor clearColor];
    
    if (component == FirstComponent) {
        NSDictionary *firstDic =[self.firstRegion objectAtIndex:row];
        myView.text = firstDic[@"localName"];
    }else if (component == SubComponent) {
        NSDictionary *subDic =[self.secondRegion objectAtIndex:row];
        myView.text = subDic[@"localName"];
    }else if (component == ThirdComponent){
        NSDictionary *thirdDic =[self.thridRegion objectAtIndex:row];
        myView.text = thirdDic[@"localName"];
    }
    return myView;
}


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component==FirstComponent) {
        return [self.firstRegion count];
    }
    if (component==SubComponent) {
        return [self.secondRegion count];
    }
    if (component==ThirdComponent) {
        return [self.thridRegion count];
    }
    return 0;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    CGFloat componentWidth = 0.0;
    
    if (component==FirstComponent) {
        componentWidth = 100.0;
    }
    if (component==SubComponent) {
        componentWidth = 90.0;
    }
    if (component==ThirdComponent) {
        componentWidth = 110.0;
    }
    return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 30.0;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
@end
